package com.wkhyapp.lm;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.wkhyapp.lm.base.SuperActivity;
import com.wkhyapp.lm.constant.Constant;
import com.wkhyapp.lm.contract.MainPresenter;
import com.wkhyapp.lm.contract.MainView;
import com.wkhyapp.lm.fragment.CategoryFragment;
import com.wkhyapp.lm.fragment.DynamicFragment;
import com.wkhyapp.lm.fragment.IndexFragment;
import com.wkhyapp.lm.fragment.MyFragment;
import com.wkhyapp.lm.utils.MemberUtils;
import com.wkhyapp.lm.utils.PreferenceUtils;
import com.wkhyapp.lm.utils.StatusBarUtil;
import com.wkhyapp.lm.view.WebViewActivity;
import com.wkhyapp.lm.weigit.dialog.ExplainDialog;
import com.wkhyapp.lm.weigit.dialog.XieyiDialog;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;


public class MainActivity extends SuperActivity<MainPresenter> implements MainView, RadioGroup.OnCheckedChangeListener{

    //C:\Program Files (x86)\MuMu\emulator\nemu\vmonitor\bin
    //C:\Program Files\MuMu\emulator\nemu\vmonitor\bin
    //adb_server connect 127.0.0.1:7555

    private Fragment mContent;
    private IndexFragment indexFragment;
    private CategoryFragment categoryFragment;
    private MyFragment myFragment;
    private DynamicFragment dynamicFragment;

    static final String FRAGMENTS_TAG = "android:support:fragments";
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.index_rb)
    RadioButton index_rb;
    @BindView(R.id.my_rb)
    RadioButton my_rb;
    @BindView(R.id.category_rb)
    RadioButton category_rb;

    public static MainActivity mainActivity;
    @Override
    public void initUI() {
        translucentStatusBar();
        StatusBarUtil.transparencyBar(this);
        StatusBarUtil.StatusBarLightMode(this);
        mainActivity = this;
        if(!PreferenceUtils.getInstance().getPrefBoolean("open",false)){
            final XieyiDialog xieyiDialog   = new XieyiDialog(mContext);
            xieyiDialog.show();
            xieyiDialog.setCallBack(new XieyiDialog.callBack() {
                @Override
                public void jump() {
                    finish();

                }

                @Override
                public void close() {
                    PreferenceUtils.getInstance().setPrefBoolean("open",true);
                    xieyiDialog.close();
                }

                @Override
                public void xiey(int type) {
                    if(type ==1){
                        goTo(WebViewActivity.class,"http://img.wkhyw.com/yhxy.html","用户协议");
                    }else{
                        goTo(WebViewActivity.class,"http://img.wkhyw.com/yssm.html","隐私声明");
                    }
                }
            });
        }
        if(MemberUtils.isLogin()){
            if(!PreferenceUtils.getInstance().getPrefBoolean("show",false)) {
                final ExplainDialog explainDialog = new ExplainDialog(mContext);
                explainDialog.show();
                explainDialog.setCallBack(new ExplainDialog.callBack() {
                    @Override
                    public void jump() {
                        PreferenceUtils.getInstance().setPrefBoolean("show", true);
                        explainDialog.close();

                    }
                });
            }
        }

        Constant.channelName = getChannelName(this);
    }

    /**
     * 获取友盟渠道名
     *
     * @param ctx 此处习惯性的设置为activity，实际上context就可以
     * @return 如果没有获取成功，那么返回值为空
     */
    public static String getChannelName(Activity ctx) {
        if (ctx == null) {
            return null;
        }
        String channelName = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        //此处这样写的目的是为了在debug模式下也能获取到渠道号，如果用getString的话只能在Release下获取到。
                        channelName = applicationInfo.metaData.get("UMENG_CHANNEL") + "";
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelName;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            savedInstanceState.putParcelable(FRAGMENTS_TAG, null);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initListener() {
        radioGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.index_rb:
                replaceFragment(indexFragment);
                break;
            case R.id.category_rb:
                replaceFragment(categoryFragment);
                break;
            case R.id.dynamic_rb:
                replaceFragment(dynamicFragment);
                break;
            case R.id.my_rb:
                replaceFragment(myFragment);
                break;
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    private void replaceFragment(Fragment fragment) {
        if (!fragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().hide(mContent).add(R.id.fragment_container, fragment).commit();
        } else {
            getSupportFragmentManager().beginTransaction().hide(mContent).show(fragment).commit();
        }
        mContent = fragment;
    }

    @Override
    protected MainPresenter createPresenter() {
        return mPresenter = new MainPresenter(this);
    }

    @Override
    protected void afterCreate() {
        if (indexFragment == null) {
            indexFragment = new IndexFragment();
        }

        if (myFragment == null) {
            myFragment = new MyFragment();
        }
        if (categoryFragment == null) {
            categoryFragment = new CategoryFragment();
        }

        if (dynamicFragment == null) {
            dynamicFragment = new DynamicFragment();
        }
        index_rb.setChecked(true);
        //决定哪个界面
        String flag = getIntent().getStringExtra("0");
        if (isEmpty(flag)) {
            mContent = indexFragment;
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, indexFragment).commit();
        }else if (flag.equals("MY")) {
            mContent = myFragment;
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).commit();
            my_rb.setChecked(true);
        }


    }

    @Override
    public void onResume() {
        super.onResume();

    }

    /**
     * 菜单、返回键响应
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        exitBy2Click(); // 调用双击退出函数
        return false;
    }

    private static Boolean isExit = false;
    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            TToast("再按一次退出程序");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
          finish();

        }
    }
}
